/**
 * @description 一行多个输入框事件模板
 * @example 久期异常（净值拟合）
 * @author muisuidaan
 */

import styled from "styled-components";

// import SInput from "../Input";
import { Fragment, useEffect, useState } from "react";
import { RedBtn } from "../Button";
import { BottomCard } from "./BottomCard";
import { RedTitle } from "../Title/redTitile";
import SInputNumber from '../Input/InputNumber';
import {ToFixNumber,IsExitUnit,UNIT_LIST,UNIT_LIST_FLECT} from "@/utils/utils";
import { collectErrors } from './InlineInput'


// 适合此模板的事件代码
export const EVENT_INLINE_INPUT = [
  "duration_alert_predicted", // 久期异常（净值拟合）-个基
  "stock_consensus_alert", // 股票一致性预期变化 -个基
];
const EVENT_INLINE_MAP = {
  duration_alert_predicted: {
    key1: "gapDay",
    key2: "thresholdLower",
    key3: "thresholdUpper",
    value1: "根据基金净值拟合推算的久期，连续",
    value2: "日",
    value1_2:'＜',
    value3: "",
    value3_4:"或者＞",
    value4: "年",
  },
  stock_consensus_alert: {
    key1: "heavyStock",
    key2: "oneMThreshold",
    key3: "threeMThreshold",
    value1: "持仓超过",
    value2: "%",
    value1_2:'的重仓股票一致性预期营收、净利润近一月变动超出',
    value3: "%",
    value3_4:"，近三月变动超出",
    value4: "%",
  },
};
const Box = styled.div`
  width: 100%;
  background: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  padding: 12px;
  color: #35425E;
  margin-top: 8px;
`;
export const FlexDiv = styled.div`
  display: flex;
  align-items: center;
  margin-top: ${(props) => props.mt || "0"};
`;

const RowMultipleInput = (props: any) => {
  console.log("props", props);
  const { thresholdValue, onSubmit, eventInfo, enable } = props;
  const { value = "duration_alert_predicted" } = eventInfo || {};

  const [saveParams, setSaveParams] = useState({ ...thresholdValue });

  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);

  useEffect(() => {
    setSaveParams({
      ...thresholdValue,
    });
    setErrorList([])
    setIsChanged(false);
  }, [thresholdValue]);

  useEffect(() => {
    if(enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true)
    }
  },[enable])

  const onChange = (val: string | number | null, key: string) => {
    handleCollectErrors(val?.toString(), key)
    setIsChanged(true)
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || '',
      }
    })
  }

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams)
    setErrorList([...new Set(res)])
    return [...new Set(res)];
  }

  const onClick = () => {
    const res = handleCollectErrors();
    console.log("res", res, errorList.length > 0 || res.length > 0);

    if (errorList.length > 0 || res.length > 0 ||!isChanged) return;
    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: saveParams,
      dataMemo: createInfoText(false),
    });
  };
  console.log(errorList);

  //通过参数生成说明文案
  const createInfoText = (html: boolean) => {
    let str = `<p>* ${EVENT_INLINE_MAP[value]?.value1} <em>${
      ToFixNumber(saveParams[EVENT_INLINE_MAP[value]?.key1])
    }${EVENT_INLINE_MAP[value]?.value2} </em> ${EVENT_INLINE_MAP[value]?.value1_2} <em>${
      ToFixNumber(saveParams[EVENT_INLINE_MAP[value]?.key2])
    }${
      EVENT_INLINE_MAP[value]?.value3
    } </em> ${EVENT_INLINE_MAP[value]?.value3_4} <em> ${ToFixNumber(saveParams[EVENT_INLINE_MAP[value]?.key3])}${
      EVENT_INLINE_MAP[value]?.value4
    } </em> 。</p>`;
    if (!html) {
      str = str
        .replaceAll("<p>", "")
        .replaceAll("</p>", "")
        .replaceAll("<em>", "")
        .replaceAll("</em>", "")
        .replace(/\s+/g,"")
    }

    return str;
  };
  
  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <span>{EVENT_INLINE_MAP[value]?.value1}</span>
          <SInputNumber
            value={saveParams[EVENT_INLINE_MAP[value]?.key1]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key1)}
            onChange={(e) =>
              onChange(e, EVENT_INLINE_MAP[value]?.key1)
            }
            min={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)]?.min
            }
            max={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)]?.max
            }
            
            precision={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
              ]?.count
            }
            // unit={IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)}
            // step={
            //   UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)]?.step

            // }
            // formatter={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)]?.count;

            //   return parseFloat(val).toFixed(count);

            // }}
            // parser={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value2,UNIT_LIST)]?.count;
            //   return parseFloat(val).toFixed(count);

            // }}
            // controls={false}
            // stringMode
          />
          <span>{EVENT_INLINE_MAP[value]?.value2}{EVENT_INLINE_MAP[value]?.value1_2}</span>
          <SInputNumber
            value={saveParams[EVENT_INLINE_MAP[value]?.key2]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key2)}
            onChange={(e) =>
              onChange(e, EVENT_INLINE_MAP[value]?.key2)
            }
            min={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)]?.min
            }
            max={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)]?.max
            }
            precision={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value3, UNIT_LIST)
              ]?.count
            }
            // unit={IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)}
            // step={
            //   UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)]?.step

            // }
            // formatter={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)]?.count;

            //   return parseFloat(val).toFixed(count);

            // }}
            // parser={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value3,UNIT_LIST)]?.count;
            //   return parseFloat(val).toFixed(count);

            // }}
            // controls={false}
            // stringMode
          />
          <span>{EVENT_INLINE_MAP[value]?.value3}{EVENT_INLINE_MAP[value]?.value3_4}</span>
          <SInputNumber
            value={saveParams[EVENT_INLINE_MAP[value]?.key3]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key3)}
            onChange={(e) =>
              onChange(e, EVENT_INLINE_MAP[value]?.key3)
            }
            min={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)]?.min
            }
            max={
              UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)]?.max
            }
            
            precision={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
              ]?.count
            }
            // unit={IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)}
            // step={
            //   UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)]?.step

            // }
            // controls={false}
            // stringMode
            // formatter={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)]?.count;

            //   return parseFloat(val).toFixed(count);

            // }}
            // parser={(val) =>{
            //   const count = UNIT_LIST_FLECT[IsExitUnit(EVENT_INLINE_MAP[value]?.value4,UNIT_LIST)]?.count;
            //   return parseFloat(val).toFixed(count);

            // }}
          />
          
          <span>{EVENT_INLINE_MAP[value]?.value4}</span>
        </FlexDiv>

        {/* 底部说明文案 */}
        <BottomCard info={createInfoText(true)}></BottomCard>
      </Box>
      <FlexDiv style={{ marginTop: 12, alignItems: "flex-end" }}>
        <RedBtn disabled={!isChanged} onClick={onClick} >
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged && <RedTitle eventInfo={eventInfo}></RedTitle >}
      </FlexDiv>
    </Fragment>
  );
};

export default RowMultipleInput;
